/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import os from 'os';

/**
 * 打印error信息并退出执行,直接throw error会打出多余堆栈信息
 *
 * @param error
 */
export function logErrorAndExit(error: unknown) {
  if (error instanceof Error) {
    console.error(error.message);
  } else {
    console.error(error);
  }
  process.exit(-1);
}

/**
 * 打印log日志(wrapper命令行工具专用)
 * 一般场景不建议使用console打印日志，
 *
 * @param log
 */
export function logInfo(log: string) {
  console.log(log);
}

/**
 * 打印error日志(wrapper命令行工具专用)
 * 一般场景不建议使用console打印日志，
 *
 * @param log
 */
export function logError(log: string) {
  console.error(log);
}

export function logFormatedError(code: string, message: string, solutions: string[]) {
  let errMsg = '';
  const red = '\u001b[31m';
  const reset = '\u001b[39m';

  const errorTypeCode = getErrorTypeCodeFromErrorCode(code);
  let description = ''
  if (errorTypeCode) {
    const errorCodeDescription = ErrorCodeDescription[errorTypeCode as ErrorCode];
    description = errorCodeDescription ?? description;
  }

  errMsg += `${red}> hvigor ERROR: ${code} ${description}`;
  errMsg += `${red}${os.EOL}Error Message: ${message}`;
  errMsg += `${red}${os.EOL}${os.EOL}* Try the following: `;
  solutions.forEach(solution => {
    errMsg += `${red}${os.EOL}  > ${solution}${reset}`;
  });

  console.error(errMsg);
}

export function logFormatedErrorAndExit(code: string, message: string, solutions: string[]) {
  logFormatedError(code, message, solutions);
  process.exit(-1);
}

function getErrorTypeCodeFromErrorCode(errorCode: string) {
  if (!errorCode || errorCode.length < 5) {
    return;
  }
  return errorCode.slice(3, 5);
}

enum ErrorCode {
  ERROR_00 = '00',
  ERROR_01 = '01',
  ERROR_02 = '02',
  ERROR_03 = '03',
  ERROR_04 = '04',
  ERROR_05 = '05',
  ERROR_06 = '06',
  ERROR_07 = '07',
  ERROR_08 = '08',
}

// 将错误码映射到描述信息
const ErrorCodeDescription: Record<ErrorCode, string> = {
  [ErrorCode.ERROR_00]: 'Unknown Error',
  [ErrorCode.ERROR_01]: 'Dependency Error',
  [ErrorCode.ERROR_02]: 'Script Error',
  [ErrorCode.ERROR_03]: 'Configuration Error',
  [ErrorCode.ERROR_04]: 'Not Found',
  [ErrorCode.ERROR_05]: 'Syntax Error',
  [ErrorCode.ERROR_06]: 'Specification Limit Violation',
  [ErrorCode.ERROR_07]: 'Permissions Error',
  [ErrorCode.ERROR_08]: 'Operation Error',
};
